package com.tcts;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;
import javax.xml.stream.events.EndDocument;

public class UrlFilter implements Filter {
	private String imgFormat[]={"BMP","PCX","TIFF","GIF","JPEG","TGA","EXIF","FPX","SVG","PSD","CDR","PCD","DXF","UFO","EPS","AI","PNG","HDRI","RAW"};
	private static final String LOCAL_HOST_ONE = "tctsthrough.com";//"tctsthrough.wicp.net";//.com";
	private static final String LOCAL_HOST_TWO = "tctsthrough.cn";
	private static final String TARGET_HOST_ONE = "mogujie.com";
	private static final String TARGET_HOST_TWO = "mogujie.cn";
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest srequest, ServletResponse sresponse,
			FilterChain filterchain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest request = (HttpServletRequest) srequest;
		HttpServletResponse response = (HttpServletResponse) sresponse;
		response.setCharacterEncoding("UTF_8");// 设置Response的编码方式为UTF-8
		response.setHeader("Content-type", "text/html;charset=UTF-8");// 向浏览器发送一个响应头，设置浏览器的解码方式为UTF-8,其实设置了本句，也默认设置了Response的编码方式为UTF-8，但是开发中最好两句结合起来使用
		
		String url = request.getRequestURL().toString();   
		
		System.out.println("User-Agent : " + request.getHeader("User-Agent"));
		 
		int index = url.lastIndexOf(".");
		String suffix = url.substring(index+1);
		for (int i = 0; i < imgFormat.length; i++) {
			if(suffix.equals(imgFormat[i])){
				String rootPath = request.getServletPath(); 
				File file = new File(getImagePath(url, rootPath));
				if(file.exists()){
					filterchain.doFilter(srequest, sresponse); 
					return;
				}
				url=url.replace(LOCAL_HOST_ONE, TARGET_HOST_ONE); 
				getImage(url,rootPath,suffix);
				break;
			}
		}
		PrintWriter out = response.getWriter();
		if(url.equals("http://www.tctsthrough.com/robots.txt")){
			filterchain.doFilter(srequest, sresponse); 
		}else {
			DealService dealService = new DealService();
			dealService.mgetPage(url, out); 
			// 需要过滤的代码
			return;
		}
		// filterchain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}
	
	private void getImage(String imgUrl,String rootPath,String format){
		
    	try {
    		ByteArrayOutputStream imageWriter = new ByteArrayOutputStream();
    		BufferedImage image = ImageIO.read(new URL(imgUrl));
    		//String rPath="D:\\tomcat\\apache-tomcat-7.0.47\\webapps\\TCTS\\img\\";
    		File file = new File(getPath(imgUrl, rootPath));
    		if(!file.exists())
    			file.mkdirs(); 
			ImageIO.write(image, format, file);
			ImageIO.write(image, format, imageWriter);
			imageWriter.close();  
		} catch (MalformedURLException e) {
			System.out.println("图片获取异常");
		} catch (IOException e) {
			System.out.println("图片存储异常");
		} 
	}
	
	private String getPath(String imgUrl,String rootPath){
		int nameIndex = imgUrl.lastIndexOf("/"); 
		int relativeIndex=imgUrl.indexOf(10);
		String relativePath = imgUrl.substring(relativeIndex+1, nameIndex);
		return rootPath+relativePath;
	}
	
	private String getImagePath(String imgUrl,String rootPath){
		int nameIndex = imgUrl.lastIndexOf("/");
		int formatIndex = imgUrl.lastIndexOf(".");
		String name = imgUrl.substring(nameIndex+1, formatIndex); 
		return getPath(imgUrl, rootPath)+"/"+name;
	}

}
